<?php

namespace app\common\model\mall\user;

use think\Model;

class Favorite extends Model
{
    // 表名
    protected $name = 'mall_user_favorite';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = "int";

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'url',
        'type_text',
        'status_text'
    ];

    public function getTypeList()
    {
        return ['goods' => __('Goods'),'shop' => __('Shop'),'help' => __('Help'),'cms_news' => __('Cms_news'),'cms_product' => __('Cms_product'),'cms_download' => __('Cms_download'),'outlink' => __('Outlink')];
    }

    public function getStatusList()
    {
        return ['open' => __('Open'),'friend' => __('Friend'),'private' => __('Private')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getUrlAttr($value, $data)
    {
        switch ($data["type"]){
            case "goods":
                $url = addon_url('mall/goods/detail', [':ids' => $data['target']]);
                break;
            case "shop":
                $url = addon_url('mall/shop/detail', [':ids' => $data['target']]);
                break;
            case "help":
                $url = addon_url('mall/help/detail', [':ids' => $data['target']]);
                break;
            case "cms_news":
                $url = addon_url('cms/article/detail', [':model_id'=>1,':ids' => $data['target']]);
                break;
            case "cms_product":
                $url = addon_url('cms/article/detail', [':model_id'=>2,':ids' => $data['target']]);
                break;
            case "cms_download":
                $url = addon_url('cms/article/detail', [':model_id'=>3,':ids' => $data['target']]);
                break;
            default:
                $url = $data['target'];
        }
        return $url;
    }

    /**
     * 判断是否已关注
     */
    public function checkFavorite($id,$type,$uId=0){
        $user_id = ($uId==0)?(int)cookie('uid'):$uId;
        $rs = $this->where(['user_id'=>$user_id,'type'=>$type,'target'=>$id])->find();
        return empty($rs)?0:$rs['id'];
    }

    /**
     * 关注数
     */
    public function followNum($id,$type){
        $rs = $this->where(['type'=>$type,'target'=>$id])->count();
        return $rs;
    }

}
